<template>
  <div class="login">
    <!-- 登录页头部 -->
    <div class="login-header">
      <div class="flex-y-c">
        <el-image :src="logo" class="logo" />
        <span class="title">
          {{ defaultSettings.title }}
        </span>
        <el-tag size="small" type="success">
          {{ defaultSettings.version }}
        </el-tag>
      </div>

      <el-switch v-model="isDark" inline-prompt active-icon="ep-Moon" inactive-icon="ep-Sunny" @change="toggleTheme" />
    </div>
    <!-- 登录页内容 -->
    <div class="login-content">
      <!-- <div class="login-img">
        <el-image :src="loginImage" style="width: 210px" />
      </div> -->
      <div class="login-form">
        <el-form ref="loginFormRef" :model="loginData" :rules="loginRules">
          <div class="form-title">
            登 录
            <el-dropdown style="position: absolute; right: 0">
              <div class="cursor-pointer" :class="{ hidden: isProduction }">
                <el-icon><ep-ArrowDown /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="setLoginCredentials('atsmsadmin', '123456')">超级管理员：atsmsadmin/123456</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <!-- 用户名 -->
          <el-form-item prop="username">
            <div class="input-wrapper">
              <el-icon class="mx-10">
                <ep-User />
              </el-icon>
              <el-input ref="username" v-model="loginData.username" placeholder="用户名" name="username" size="large" class="h-[48px]" />
            </div>
          </el-form-item>

          <!-- 密码 -->
          <el-tooltip :visible="isCapsLock" content="大写锁定已打开" placement="right">
            <el-form-item prop="password">
              <div class="input-wrapper">
                <el-icon class="mx-10">
                  <ep-Lock />
                </el-icon>
                <el-input
                  v-model="loginData.password"
                  placeholder="密码"
                  type="password"
                  name="password"
                  size="large"
                  class="h-[48px] pr-8"
                  show-password
                  @keyup="checkCapsLock"
                  @keyup.enter="handleLoginSubmit"
                />
              </div>
            </el-form-item>
          </el-tooltip>

          <div class="flex-x-between w-full py-1">
            <el-checkbox v-model="checked">记住我</el-checkbox>
            <!-- <el-link type="primary" href="/forget-password">忘记密码</el-link> -->
          </div>

          <!-- 登录按钮 -->
          <el-button :loading="loading" type="primary" size="large" class="w-full" @click.prevent="handleLoginSubmit">登 录</el-button>

          <!-- 第三方登录 -->
          <!-- <el-divider>
            <el-text size="small">其他登录方式</el-text>
          </el-divider>
          <div class="third-party-login">
            <c-wechat class="icon" />
          </div> -->
        </el-form>
      </div>
    </div>

    <!-- <div class="login-footer">
      <el-text size="small">
        Copyright © 2023 深圳市汉德网络科技有限公司 版权所有.
        <el-link :underline="false" href="http://beian.miit.gov.cn/" target="_blank">粤公网安备 44030602007595号</el-link>
      </el-text>
    </div> -->
  </div>
</template>

<script lang="ts" setup>
import { LocationQuery } from 'vue-router'
import { useSettingsStore, useUserStore } from '@/store'
import defaultSettings from '@/utils/settings'
import { ThemeEnum } from '@/enums/ThemeEnum'
import Storage from '@/utils/Storage'
import { LOGIN_USERNAME_KEY, LOGIN_PASSWORD_KEY } from '@/utils/constant'

import type { FormInstance } from 'element-plus'
import type { LoginData } from '@/api/auth'

const userStore = useUserStore()
const settingsStore = useSettingsStore()
const loginFormRef = ref<FormInstance>()
const route = useRoute()
const router = useRouter()

const logo = ref(new URL('../../assets/logo.png', import.meta.url).href)
// const loginImage = ref(new URL('../../assets/images/login-image.svg', import.meta.url).href)

const isProduction = ref(import.meta.env.MODE === 'production') // 是否暗黑模式
const isDark = ref(settingsStore.theme === ThemeEnum.DARK) // 是否暗黑模式
const loading = ref(false) // 按钮 loading 状态
// const captchaBase64 = ref() // 验证码图片Base64字符串
const isCapsLock = ref(false) // 是否大写锁定
const checked = ref(settingsStore.rememberChecked) // 记住密码

const loginData = ref<LoginData>({
  // username: 'atsmsadmin',
  // password: '123456'
  username: '',
  password: ''
})

const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入用户名'
      }
    ],
    password: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入密码'
      },
      {
        min: 6,
        message: '密码不能少于6位',
        trigger: 'blur'
      }
    ]
    // captchaCode: [
    //   {
    //     required: true,
    //     trigger: 'blur',
    //     message: '请输入验证码'
    //   }
    // ]
  }
})

/** 登录表单提交 */
async function handleLoginSubmit() {
  loginFormRef.value?.validate(valid => {
    if (valid) {
      loading.value = true
      userStore
        .login(loginData.value)
        .then(async () => {
          // await userStore.getUserInfo()
          if (checked.value) {
            Storage.setStorage(LOGIN_USERNAME_KEY, loginData.value.username)
            Storage.setStorage(LOGIN_PASSWORD_KEY, loginData.value.password)
          } else {
            Storage.remove(LOGIN_USERNAME_KEY)
            Storage.remove(LOGIN_PASSWORD_KEY)
          }
          settingsStore.changeRememberChecked(checked.value)
          // 跳转到登录前的页面
          const { path, queryParams } = parseRedirect()
          router.push({ path: path, query: queryParams })
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

// 设置登录凭证
const setLoginCredentials = (username: string, password: string) => {
  loginData.value.username = username
  loginData.value.password = password
}

// 检查输入大小写
function checkCapsLock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapsLock.value = event.getModifierState('CapsLock')
  }
}

// 主题切换
const toggleTheme = () => {
  const newTheme = settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK
  settingsStore.changeTheme(newTheme)
}

/**
 * 解析 redirect 字符串 为 path 和  queryParams
 */
function parseRedirect(): { path: string; queryParams: Record<string, string> } {
  const query: LocationQuery = route.query
  const redirect = (query.redirect as string) ?? '/'

  const url = new URL(redirect, window.location.origin)
  const path = url.pathname
  const queryParams: Record<string, string> = {}

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value
  })

  return { path, queryParams }
}

onMounted(() => {
  const username = Storage.getStorage(LOGIN_USERNAME_KEY)
  const password = Storage.getStorage(LOGIN_PASSWORD_KEY)

  if (checked.value && username && password) {
    loginData.value.username = username
    loginData.value.password = password + ''
  }
})
</script>
<style lang="scss" scoped>
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  // background: url('@/assets/images/login-background-light.jpg') no-repeat center right;
  background: url('@/assets/images/bg.png') no-repeat center right;
  background-size: cover;

  .login-header {
    position: absolute;
    top: 0;
    display: flex;
    justify-content: space-between;
    width: 100%;
    padding: 15px;

    .logo {
      width: 26px;
      height: 26px;
    }

    .title {
      margin: auto 5px;
      font-size: 26px;
      font-weight: bold;
      color: transparent;
      background: linear-gradient(to right, #3b82f6, #14b8a6);
      background-clip: text;
      -webkit-text-fill-color: transparent;
    }
  }

  .login-content {
    // display: flex;
    // width: 850px;
    overflow: hidden;
    background: rgba($color: #ffffff, $alpha: 0.9);
    border-radius: 5px;
    // box-shadow: var(--el-box-shadow-light);
    // transform: translateX(-50%);

    @media (width <= 768px) {
      // flex-direction: column;
      max-width: 100%;
      border-radius: 0;
      box-shadow: none;
    }

    .login-img {
      display: flex;
      flex: 3;
      align-items: center;
      justify-content: center;
      background: linear-gradient(60deg, #165dff, #6aa1ff);

      @media (width <= 768px) {
        display: none;
      }
    }

    .login-form {
      display: flex;
      // flex: 2;
      flex-direction: column;
      justify-content: center;
      min-width: 500px;
      padding: 30px;

      @media (width <= 768px) {
        min-width: 400px;
      }

      .form-title {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 20px 0;
        font-size: 20px;
        text-align: center;
      }

      .input-wrapper {
        display: flex;
        align-items: center;
        width: 100%;
      }

      .captcha-img {
        height: 48px;
        cursor: pointer;
        border-top-right-radius: 6px;
        border-bottom-right-radius: 6px;
      }

      .third-party-login {
        display: flex;
        justify-content: center;
        width: 100%;
        color: var(--el-text-color-secondary);

        *:not(:first-child) {
          margin-left: 20px;
        }

        .icon {
          cursor: pointer;
        }
      }
    }
  }

  .login-footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    text-align: center;
  }
}

:deep(.el-form-item) {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      /* 通过延时渲染背景色变相去除背景颜色 */
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}

html.dark {
  .login {
    background: url('@/assets/images/login-background-dark.jpg') no-repeat center right;

    .login-content {
      background: transparent;
      box-shadow: var(--el-box-shadow);
    }
  }
}
</style>
